<template>
  <div class="file-message" :class="{ 'own-message': isOwn }">
    <!-- 消息头部信息 -->
    <div v-if="!isOwn" class="message-header">
      <el-avatar
        :size="32"
        :src="message.senderAvatar"
        :alt="message.senderName"
      >
        {{ message.senderName?.charAt(0) }}
      </el-avatar>
      <div class="sender-info">
        <span class="sender-name">{{ message.senderName }}</span>
        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
      </div>
    </div>

    <!-- 消息内容 -->
    <div class="message-content">
      <div class="message-bubble" :class="{ 'own-bubble': isOwn }">
        <!-- 文件信息 -->
        <div class="file-container" @click="downloadFile">
          <div class="file-icon">
            <el-icon :size="32">
              <component :is="getFileIcon()" />
            </el-icon>
          </div>
          
          <div class="file-info">
            <div class="file-name" :title="message.fileName">
              {{ message.fileName || '未知文件' }}
            </div>
            <div class="file-details">
              <span v-if="message.fileSize" class="file-size">
                {{ formatFileSize(message.fileSize) }}
              </span>
              <span class="file-type">
                {{ getFileExtension() }}
              </span>
            </div>
          </div>
          
          <div class="file-actions">
            <el-button
              type="primary"
              :icon="isDownloading ? Loading : Download"
              size="small"
              :loading="isDownloading"
              :disabled="isDownloading"
              @click.stop="downloadFile"
            >
              {{ isDownloading ? '下载中' : '下载' }}
            </el-button>
          </div>

          <!-- 下载进度条 -->
          <div v-if="isDownloading" class="download-progress">
            <div class="progress-header">
              <span class="progress-text">下载中... {{ downloadProgress }}%</span>
              <el-button
                size="small"
                type="danger"
                :icon="Close"
                @click="cancelDownload"
                title="取消下载"
              />
            </div>
            <el-progress
              :percentage="downloadProgress"
              :stroke-width="4"
              :show-text="false"
              status="success"
            />
          </div>
        </div>
        
        <!-- 消息状态（仅自己的消息显示） -->
        <div v-if="isOwn" class="message-status">
          <el-icon v-if="message.messageStatus === 'sending'" class="status-sending">
            <Loading />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'sent'" class="status-sent">
            <Check />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'failed'" class="status-failed">
            <Close />
          </el-icon>
          <span class="message-time">{{ formatTime(message.timestamp) }}</span>
        </div>
      </div>
    </div>

    <!-- 消息操作菜单 -->
    <div class="message-actions" v-show="showActions">
      <el-button-group size="small">
        <el-button :icon="ChatLineRound" @click="replyMessage" title="回复">
        </el-button>
        <el-button :icon="Download" @click="downloadFile" title="下载">
        </el-button>
        <el-button 
          v-if="isOwn" 
          :icon="Delete" 
          @click="deleteMessage" 
          title="删除"
          type="danger"
        >
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Loading,
  Check,
  Close,
  Download,
  Document,
  VideoPlay,
  Headset,
  Files,
  Picture,
  ChatLineRound,
  Delete
} from '@element-plus/icons-vue'

// 类型定义
interface TeamMessage {
  id: number | string
  teamId: number
  senderId: number
  senderName: string
  senderAvatar?: string
  messageType: 'text' | 'image' | 'file'
  content: string
  fileName?: string
  fileSize?: number
  fileUrl?: string
  messageStatus: 'sending' | 'queued' | 'sent' | 'delivered' | 'failed'
  timestamp: number
  // 加密相关字段
  iv?: string
  encryptionAlgorithm?: string
  keyVersion?: number
  isEncrypted?: boolean
}

// Props
interface Props {
  message: TeamMessage
  isOwn: boolean
}

const props = defineProps<Props>()

// 调试信息
console.log('📄 FileMessage组件接收到的消息数据:', props.message)

// 响应式数据
const showActions = ref(false)

// 计算属性
const getFileExtension = () => {
  if (!props.message.fileName) return ''
  const parts = props.message.fileName.split('.')
  return parts.length > 1 ? parts.pop()?.toUpperCase() : ''
}

const getFileIcon = () => {
  const fileName = props.message.fileName?.toLowerCase() || ''
  const extension = getFileExtension()?.toLowerCase()
  
  // 图片文件
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(extension || '')) {
    return Picture
  }
  
  // 视频文件
  if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(extension || '')) {
    return VideoPlay
  }
  
  // 音频文件
  if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(extension || '')) {
    return Headset
  }
  
  // 压缩文件
  if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension || '')) {
    return Files
  }
  
  // 默认文档图标
  return Document
}

// 方法
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟显示"刚刚"
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时显示分钟
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 小于24小时显示小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  
  // 今天显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })}`
  }
  
  // 其他显示日期时间
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 下载状态
const downloadProgress = ref(0)
const isDownloading = ref(false)
const downloadController = ref<AbortController | null>(null)

const downloadFile = async () => {
  try {
    console.log('📥 开始下载文件:', props.message)

    const fileUrl = props.message.fileUrl
    const fileName = props.message.fileName || `file_${props.message.id}`

    if (!fileUrl) {
      ElMessage.error('文件URL不存在，无法下载')
      return
    }

    // 确保URL格式正确，匹配后端Controller路径
    let correctedUrl = fileUrl

    // 如果是旧格式 /api/files/download/{id}，转换为新格式 /api/files/{id}/download
    if (fileUrl.match(/^\/api\/files\/download\/\d+$/)) {
      const fileId = fileUrl.split('/').pop()
      correctedUrl = `/api/files/${fileId}/download`
    }

    // 确保URL是完整的
    const fullUrl = correctedUrl.startsWith('http') ? correctedUrl : `${window.location.origin}${correctedUrl}`

    console.log('📥 下载URL:', fullUrl)
    console.log('📥 文件名:', fileName)

    // 开始下载
    isDownloading.value = true
    downloadProgress.value = 0

    // 创建下载控制器
    downloadController.value = new AbortController()

    // 使用fetch下载并显示进度
    const response = await fetch(fullUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`,
        'Cache-Control': 'no-cache'
      },
      signal: downloadController.value.signal
    })

    if (!response.ok) {
      throw new Error(`下载失败: ${response.status} ${response.statusText}`)
    }

    const contentLength = response.headers.get('content-length')
    const total = contentLength ? parseInt(contentLength, 10) : 0

    if (!response.body) {
      throw new Error('响应体为空')
    }

    const reader = response.body.getReader()
    const chunks: Uint8Array[] = []
    let receivedLength = 0

    // 读取数据流并更新进度
    while (true) {
      const { done, value } = await reader.read()

      if (done) break

      chunks.push(value)
      receivedLength += value.length

      // 更新下载进度
      if (total > 0) {
        downloadProgress.value = Math.round((receivedLength / total) * 100)
      }

      console.log(`📥 下载进度: ${downloadProgress.value}% (${receivedLength}/${total})`)
    }

    // 合并所有数据块
    const allChunks = new Uint8Array(receivedLength)
    let position = 0
    for (const chunk of chunks) {
      allChunks.set(chunk, position)
      position += chunk.length
    }

    // 创建Blob并下载
    const blob = new Blob([allChunks])
    const url = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理URL对象
    window.URL.revokeObjectURL(url)

    downloadProgress.value = 100
    ElMessage.success('文件下载完成')

  } catch (error: any) {
    console.error('文件下载失败:', error)

    if (error.name === 'AbortError') {
      ElMessage.warning('下载已取消')
    } else {
      ElMessage.error(`文件下载失败: ${error.message || '未知错误'}`)
    }
  } finally {
    // 延迟重置状态，让用户看到100%
    setTimeout(() => {
      isDownloading.value = false
      downloadProgress.value = 0
      downloadController.value = null
    }, 2000)
  }
}

// 取消下载
const cancelDownload = () => {
  if (downloadController.value) {
    downloadController.value.abort()
    ElMessage.info('正在取消下载...')
  }
}

const replyMessage = () => {
  // TODO: 实现回复功能
  ElMessage.info('回复功能开发中...')
}

const deleteMessage = () => {
  // TODO: 实现删除功能
  ElMessage.info('删除功能开发中...')
}
</script>

<style scoped lang="scss">
.file-message {
  position: relative;
  margin-bottom: 16px;
  
  &:hover .message-actions {
    opacity: 1;
  }

  &.own-message {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;

  .sender-info {
    display: flex;
    flex-direction: column;
    gap: 2px;

    .sender-name {
      font-size: 14px;
      font-weight: 600;
      color: var(--el-color-primary);
    }

    .message-time {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.message-content {
  position: relative;
  max-width: 400px;
  
  .own-message & {
    max-width: 400px;
  }
}

.message-bubble {
  position: relative;
  padding: 12px;
  border-radius: 12px;
  background: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color-lighter);

  &.own-bubble {
    background: var(--el-bg-color-page);
    border-color: var(--el-color-primary);
  }

  // 消息气泡箭头
  &::before {
    content: '';
    position: absolute;
    top: 12px;
    left: -8px;
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-right: 8px solid var(--el-bg-color-page);
  }

  &.own-bubble::before {
    left: auto;
    right: -8px;
    border-right: none;
    border-left: 8px solid var(--el-bg-color-page);
  }
}

.file-container {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 8px;
  background: var(--el-fill-color-lighter);
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: var(--el-fill-color-light);
    transform: translateY(-1px);
  }

  .file-icon {
    flex-shrink: 0;
    color: var(--el-color-primary);
  }

  .file-info {
    flex: 1;
    min-width: 0;

    .file-name {
      font-size: 14px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 4px;
    }

    .file-details {
      display: flex;
      gap: 8px;
      font-size: 12px;
      color: var(--el-text-color-secondary);

      .file-size {
        font-weight: 500;
      }

      .file-type {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        padding: 2px 6px;
        border-radius: 4px;
        font-weight: 600;
      }
    }
  }

  .file-actions {
    flex-shrink: 0;
  }
}

.message-status {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);

  .status-sending {
    animation: spin 1s linear infinite;
    color: var(--el-color-primary);
  }

  .status-sent {
    color: var(--el-color-success);
  }

  .status-failed {
    color: var(--el-color-error);
  }

  .message-time {
    color: var(--el-text-color-secondary);
  }
}

.message-actions {
  position: absolute;
  top: -8px;
  right: 16px;
  opacity: 0;
  transition: opacity 0.2s;
  background: var(--el-bg-color);
  border-radius: 6px;
  box-shadow: var(--el-box-shadow-light);
  z-index: 10;

  .own-message & {
    right: auto;
    left: 16px;
  }

  .el-button-group {
    .el-button {
      border-radius: 4px;
      padding: 4px 8px;
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .message-content {
    max-width: 320px;
  }

  .file-container {
    padding: 6px;
    gap: 8px;

    .file-icon {
      :deep(.el-icon) {
        font-size: 24px;
      }
    }

    .file-info .file-name {
      font-size: 13px;
    }
  }

  .message-actions {
    position: static;
    opacity: 1;
    margin-top: 8px;
    background: transparent;
    box-shadow: none;
  }
}

.download-progress {
  margin-top: 8px;
  padding: 0 4px;

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;

    .progress-text {
      font-size: 12px;
      color: var(--el-text-color-regular);
    }

    .el-button {
      padding: 2px 4px;
      min-height: 20px;

      .el-icon {
        font-size: 12px;
      }
    }
  }

  .el-progress {
    .el-progress-bar__outer {
      background-color: var(--el-border-color-lighter);
      border-radius: 2px;
    }

    .el-progress-bar__inner {
      background: linear-gradient(90deg, var(--el-color-success), var(--el-color-success-light-3));
      transition: width 0.3s ease;
      border-radius: 2px;
    }
  }
}

.file-actions {
  .el-button {
    &.is-loading {
      .el-icon {
        animation: rotating 2s linear infinite;
      }
    }
  }
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
